<?php
//****************Include files******************
include_once("../codelibrary/inc/variables.php");
include_once("../codelibrary/inc/functions.php");

// will be Changed in case server is in a different location
/*$datetime= indianDate(); 
$datetimenew = explode(" ", $datetime);
$date= $datetimenew[0];
$time =$datetimenew[1];*/


$datetime = date("Y-m-d H:i:s");
$datetimenew = explode(" ", $datetime);
$date= $datetimenew[0];
$time =$datetimenew[1];

//die();
$wherelogin=" AND UserName='$TR_User_Name'";
$rowlogin=getAnyTableWhereData($administrator_info_table,$wherelogin);
$aid=$rowlogin['AdministratorID'];
$AccessDays=$rowlogin['AccessDays'];
$LoginRetries=$rowlogin['LoginRetries'];
$datequery="Select TrailID,TrailDate from $administrator_login_trail_table where AdministratorID='$aid' order by TrailID asc limit 1";
$r=mysql_query($datequery);
$date_row=mysql_fetch_array($r);
$trailDate=$date_row['TrailDate'];
$current_date=$date;
$date_difference=datediff("d",$trailDate,$current_date);

if($AccessDays > 0)
{
    if($date_difference > $AccessDays)
    {
	  header("Location:login.php?logerr=expire");
	  exit;
    }
}
$where_login=" AND UserName='$TR_User_Name' AND Password='$TR_Password'";
$row_login=getAnyTableWhereData($administrator_info_table,$where_login);
$AdministratorID=$row_login['AdministratorID'];
$LoginIP=$REMOTE_ADDR;
$LoginTime=$time;
$TrailDate=$date;
//Re-directing the admin back to login page on login failure 
if(!$row_login)
{
	$Retries=$LoginRetries+1;
	$query="update $administrator_info_table set LoginRetries='$Retries' where AdministratorID='$aid'";
	mysql_query($query);
	
	header("Location:login.php?logerr=login");
	 
}
//Setting sessions on Successful Login
else
{
	//$LastLogin=indianDate(); 
	$LastLogin=date("Y-m-d H:i:s"); // will be Changed in case server is in a different location
    editData($administrator_info_table,"AdministratorID",$AdministratorID);
	
	/*session_register("sess_user_name");
	session_register("sess_administrator_id");
	session_register("sess_Trail_ID");
	
	
	$sess_administrator_id=$row_login["AdministratorID"];
	$sess_user_name=$row_login["UserName"];
	
	
	
	$Password=$row_login["Password"];*/
	session_register("sess_user_name");
	$sess_user_name=$row_login["UserName"];
	
	$_SESSION['UserName']=$row_login["UserName"];
	
	$_SESSION['AdministratorID']=$row_login["AdministratorID"];
	
	$_SESSION['BusinessID']=$row_login["BusinessID"];
	
	$_SESSION['Password']=$row_login["Password"];
	
	$Session_Id = session_id();
	
	
	insertData($administrator_login_trail_table);
	$sess_Trail_ID=mysql_insert_id();
	$_SESSION["sess_Trail_ID"] = $sess_Trail_ID;
	
	$Q=mysql_query("Select * from $administrator_login_trail_table where TrailID=$sess_Trail_ID");
	$R=mysql_fetch_array($Q);
	$U_ID=$R['AdministratorID'];
	
	
	
	header("location:StartPage.php?Trail_ID=$sess_Trail_ID");
}	
?>